/**
 * Angular 2 decorators and services
 */
import 'rxjs/add/operator/map';

import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {environment} from 'environments/environment';
import {Observable} from 'rxjs/Rx';
import {Subject} from 'rxjs/Subject';

import {SurveySummary} from '../../models/survey.summary';
import {SurveyService} from '../../services/survey.service';

/**
 * App Component
 * Top Level Component
 */
@Component({
  selector: 'surveylist',
  encapsulation: ViewEncapsulation.None,
  styleUrls: ['./surveylist.component.css', '../../../assets/css/font-awesome.min.css'],
  templateUrl: './surveylist.component.html'
})
export class SurveyListComponent implements OnInit {
  static DEFAULT_SORT_BY = 'createdAt';
  static DEFAULT_DIRECTION = 'DESC';

  keyword: string = '';
  sortBy: string = SurveyListComponent.DEFAULT_SORT_BY;
  direction: string = SurveyListComponent.DEFAULT_DIRECTION;
  currentPage: number = 1;
  itemCount: number = 0;
  searchTerms: Subject<string> = new Subject<string>();
  resultSurveys: Array<SurveySummary>;

  constructor(private surveySerivce: SurveyService) {}

  public ngOnInit() {
    //    this.searchTerms.debounceTime(500).distinctUntilChanged().switchMap(term => {
    //      this.keyword = term;
    //      console.log('Triggered!');
    //      return this.getSurveyServiceObserve();
    //    });
    this.fetchData();
  }

  search($event) {
    let value = $event.currentTarget.value;
    if (value === null) {
      value = '';
    }
    this.keyword = value;
    this.fetchData();
  }

  updateSortBy($event) {
    let value = $event.currentTarget.value;
    if (value === '') {
      this.sortBy = SurveyListComponent.DEFAULT_SORT_BY;
    } else {
      this.sortBy = value;
    }
    this.fetchData();
  }

  updateDirection($event) {
    let value = $event.currentTarget.value;
    if (value === '') {
      this.direction = SurveyListComponent.DEFAULT_DIRECTION;
    } else {
      this.direction = value;
    }
    this.fetchData();
  }

  updatePage($event) {
    this.currentPage = $event;
    this.fetchData();
  }

  getSurveyServiceObserve() {
    return this.surveySerivce.getSearchSurveys(
        this.keyword, this.currentPage - 1, this.sortBy, this.direction);
  }

  fetchData() {
    this.getSurveyServiceObserve().subscribe((res) => {
      this.resultSurveys = res.content;
      this.itemCount = res.totalElements;
    });
  }
}
